axios.defaults.baseURL='http://ajax-base-api-t.itheima.net'
const tbody = document.querySelector('#tb');
function renderData() {
  axios.get('/api/getbooks')
  .then(({data:res}) => {
    const { data } = res
    // console.log(res)
    console.log(data);
    const html = data.map((item) => {
      const {id, bookname,author,publisher} = item
      return `
      <tr>
      <td>${id}</td>
      <td>${bookname}</td>
      <td>${author}</td>
      <td>${publisher}</td>
      <td><a href="#" data-id=${id}>删除</a></td>
      </tr>`
    }).join('')
    tbody.innerHTML = html
  })
  .catch(err => {
    throw new Error(err)
  })
}
renderData()
//添加
const searchBtn = document.querySelector('#btnSearch');
const addBtn = document.querySelector('#btnAdd');
const form =document.querySelector('#bookForm');
form.addEventListener('submit',function (e) {
  e.preventDefault()
  if (e.target.dataset.name === 'add') {
    const data = serialize(form,{hash:true})
    axios.post('/api/addbook',data)
    .then(({data:res}) => {
      alert(res.msg)
      if(res.status!== 201) {
        return 
      }
      this.reset()
      renderData()
    })
  }
})
//删除
tbody.addEventListener('click',function (e) {
  if(e.target.tagName === 'A'){
    const id = e.target.dataset.id
    axios({
      method:'get',
      url: '/api/delbook',
      params: {
        id
      }
    }).then(({data:res}) => {
      console.log(res);
     
      alert(res.msg)
      renderData()
    })
  }
})
  //筛选
  searchBtn.addEventListener('click',function () {
    const bookname = document.querySelector('input[name=bookname]').value 
    const author = document.querySelector('input[name=author]').value
    const publisher = document.querySelector('input[name=publisher]').value
    axios({
      method:'GET',
      url: '/api/getbooks',
      params: {
        bookname,
        author,
        publisher
      }
    })
    .then(({data:res}) => {
      
      const { data } = res
      console.log(data);
      const newArr =  data.filter((item) => {
        if(item.bookname === bookname || item.author === author || item.publisher === publisher){
          return item
        }
      })

          tbody.innerHTML = ''
          const html = newArr.map((items) => {

            const {id,bookname,author,publisher} = items
            return `
            <tr>
            <td>${id}</td>
            <td>${bookname}</td>
            <td>${author}</td>
            <td>${publisher}</td>
            <td><a href="#" data-id=${id}>删除</a></td>
            </tr>`
          }).join('')
          tbody.innerHTML = html
        
      
    })
    .catch(err => {
      throw new Error(err)
    })
  })